package com.yimi.yinhepda.views.load_module;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.pda.ym.entity.bean.CarPlanTaskEntity;
import com.yimi.yinhepda.R;
import com.pda.ym.base.CommonViewHolder;
import com.yimi.yinhepda.adapter.RecycleAdapter.SetOutSealCarNewAdapter;
import com.pda.ym.base.BaseTitleActivity;
import com.pda.ym.callbacks.UICallBack;
import com.yimi.yinhepda.db.dao.CarPlateTableDao;
import com.pda.ym.db.table.CarPlateTable;
import com.yimi.yinhepda.entity.request.SealOrUnsealTaskRequest;
import com.yimi.yinhepda.entity.response.CarPlanTaskResponse;
import com.pda.ym.net.NetRequest;
import com.pda.ym.utils.CarNoSelectDialog;
import com.pda.ym.utils.Constants;
import com.pda.ym.utils.SoundVibratorManager;
import com.pda.ym.utils.StringUtils;
import com.yimi.yinhepda.views.createPackage_module.CreateDeptSelectActivity;

import org.jetbrains.annotations.NotNull;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 封车管理
 *
 * @author 000432
 * @date 2018/6/5 0005
 */

public class SetOutSealCarActivity extends BaseTitleActivity implements CommonViewHolder.onItemCommonClickListener, TextWatcher {

    /**
     * 选择下一站
     */
    private Button etSelectNextStation;
    /**
     * 车牌
     */
    private Button btnCarPlate;
    /**
     * 车牌号
     */
    private EditText etCarNo;
    /**
     * 封车列表
     */
    private RecyclerView rvListView;
    /**
     * 出发封车适配器
     */
    private SetOutSealCarNewAdapter mAdapter;
    /**
     * 出发封车列表
     */
    private List<CarPlanTaskEntity> mList;
    /**
     * 下一站网点编码
     */
    private String mNextDeptCode;
    /**
     * 下一站网点名称
     */
    private String mNextDeptName;
    /**
     * 车牌号数据操作
     */
    private CarPlateTableDao mCarPlateTableDao;
    /**
     * 选中的封车/解封实体
     */
    private CarPlanTaskEntity mSelectSealCarEntity;
    /**
     * 车牌号
     */
    private String mCarNo;
    /**
     * 临时转换的车牌号
     */
    private String mTempCarNo = "";

    @Override
    public int setContentViewId() {
        return R.layout.activity_setout_sealcar_new;
    }

    public SetOutSealCarActivity() {
        super(true);
    }

    @Override
    public String getPageName() {
        return "出发封车列表";
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initData();
    }

    /**
     * 初始化视图
     */
    private void initView() {
        etSelectNextStation = findViewById(R.id.et_select_next_station);
        etSelectNextStation.setOnClickListener(this);
        btnCarPlate = findViewById(R.id.btn_carPlate);
        btnCarPlate.setOnClickListener(this);
        etCarNo = findViewById(R.id.et_carNo);
        etCarNo.addTextChangedListener(this);
        rvListView = findViewById(R.id.rv_seal_car_list);
        //下载按钮
        findViewById(R.id.ib_seal_sign_down).setOnClickListener(this);
        //返回按钮
        findViewById(R.id.btn_back).setOnClickListener(this);
        //执行按钮
        findViewById(R.id.btn_seal_car_exec).setOnClickListener(this);
    }

    /**
     * 初始化数据
     */
    private void initData() {
        //设置车牌
        mCarPlateTableDao = new CarPlateTableDao();
        List<CarPlateTable> carPlateTables = mCarPlateTableDao.getAllData();
        if (carPlateTables != null) {
            if (carPlateTables.size() > 0) {
                btnCarPlate.setText(carPlateTables.get(0).getCarPlate());
            }
        }

        //初始化列表
        mList = new ArrayList<>();
        mAdapter = new SetOutSealCarNewAdapter(this, mList, this);
        rvListView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        rvListView.setAdapter(mAdapter);
        rvListView.setHasFixedSize(true);
        rvListView.setNestedScrollingEnabled(false);

        //获取封车请求数据
        mCarNo = getIntent().getStringExtra("carNo");
        mNextDeptCode = getIntent().getStringExtra("nextStationCode");
        mNextDeptName = getIntent().getStringExtra("nextStation");
        if (mCarNo != null && mNextDeptCode != null && mNextDeptName != null) {
            etSelectNextStation.setText(mNextDeptName);
            btnCarPlate.setText(mCarNo.substring(0, 1));
            etCarNo.setText(mCarNo.substring(1, mCarNo.length()));
            //下载封车数据
            downLoadSealCarData(mCarNo, mNextDeptCode, null);
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.et_select_next_station:
                Intent intent = new Intent(this, CreateDeptSelectActivity.class);
                intent.putExtra("currentDept", sharedPreferUtil.getDeptCode());
                intent.putExtra("inputType", 1);
                startActivityForResult(intent, 0);
                break;
            case R.id.btn_carPlate:
                //显示车牌对话框提示框
                CarNoSelectDialog.showCarPlateDialog(this, new CarNoSelectDialog.CarNoSelectListener() {
                    @Override
                    public void onclick(String carPlate) {
                        btnCarPlate.setText(carPlate);
                    }
                });
                break;
            case R.id.ib_seal_sign_down:
                //下载和刷新按钮
                String carNo = etCarNo.getText().toString();
                if (StringUtils.isEmpty(carNo)) {
                    showToast("请输入车牌号！");
                    SoundVibratorManager.playSound(2);
                    return;
                }
                etCarNo.setText(carNo.toUpperCase());
                carNo = btnCarPlate.getText().toString() + etCarNo.getText().toString();
                downLoadSealCarData(carNo, mNextDeptCode, null);
                break;
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_seal_car_exec:
                //执行按钮
                if (mSelectSealCarEntity == null || !mSelectSealCarEntity.isCheck()) {
                    showToast("请先选择一项数据！");
                    return;
                }
                Intent scanSealIntent = new Intent(SetOutSealCarActivity.this, ScanSealSignActivity.class);
                List<CarPlanTaskEntity> list = new ArrayList<>();
                list.add(mSelectSealCarEntity);
                scanSealIntent.putExtra("carPlanTaskList", (Serializable) list);
                scanSealIntent.putExtra("fromSetOutActivity", true);
                startActivity(scanSealIntent);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == 0) {
            mNextDeptCode = data.getStringExtra("deptCode");
            mNextDeptName = data.getStringExtra("deptName");
            etSelectNextStation.setText(mNextDeptName);
        }
    }

    @Override
    public void onItemClickListener(int position) {
        //设置选中状态为单选
        mSelectSealCarEntity = mList.get(position);
        if (!mSelectSealCarEntity.isCheck()) {
            for (CarPlanTaskEntity entity : mList) {
                entity.setCheck(false);
            }
            mSelectSealCarEntity.setCheck(true);
        } else {
            mSelectSealCarEntity.setCheck(false);
        }
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onItemLongClickListener(int position) {
    }

    @Override
    protected void handleBarCode(String result) {
        if (result == null) {
            SoundVibratorManager.playSound(2);
            showToast("运单号扫描失败");
        } else {
            String palletName = StringUtils.getPalletName(result);
            if (!"".equals(palletName)) {
                etCarNo.setText(result.substring(3));
                btnCarPlate.setText(palletName);
                String carNo = btnCarPlate.getText().toString() + etCarNo.getText().toString();
                downLoadSealCarData(carNo, mNextDeptCode, null);
            } else {
                doScan(result);
            }
        }
    }

    /**
     * 处理扫描结果
     */
    private void doScan(String result) {
        if (!StringUtils.isCarCodeNo(result)) {
            SoundVibratorManager.playSound(2);
            showToast("配载单号错误！");
            return;
        }
        downLoadSealCarData(null, null, result);

    }

    /**
     * 下载封车数据
     */
    private void downLoadSealCarData(String carNo, String nextDeptCode, String taskNo) {
        showPgDlg("获取数据中...");
        SealOrUnsealTaskRequest request = new SealOrUnsealTaskRequest();
        request.setCarNo(carNo);
        request.setDestDeptCode(nextDeptCode);
        request.setSrcDeptCode(sharedPreferUtil.getDeptCode());
        request.setOperTypeCode(1);
        request.setTaskNo(taskNo);

        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setResponsClazz(CarPlanTaskResponse.class)
                .setUrl(Constants.URL_V2_QUERY_SEAL_OR_UNSEAL_TASK)
                .setRequestObject(request)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        showToast(msg);
                        SoundVibratorManager.playSound(2);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        if (obj instanceof CarPlanTaskResponse) {
                            mList.clear();
                            CarPlanTaskResponse response = (CarPlanTaskResponse) obj;
                            if (response != null && response.getData() != null && !response.getData().isEmpty()) {
                                mList.addAll(response.getData());
                                SoundVibratorManager.playSound(1);
                            } else {
                                showToast("未查询到任务！");
                                SoundVibratorManager.playSound(1);
                            }
                            mAdapter.notifyDataSetChanged();
                        }
                    }
                });
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        //车牌号英文字母转换成大写
        String carNo = etCarNo.getText().toString().toUpperCase();
        if (!carNo.equalsIgnoreCase(mTempCarNo)) {
            mTempCarNo = carNo;
            etCarNo.setText(carNo);
            etCarNo.setSelection(carNo.length());
        }
    }

    @Override
    public void setBack() {
        finish();
    }

    @NotNull
    @Override
    public String setTitle() {
        return getPageName();
    }

    @Override
    public boolean showBack() {
        return false;
    }
}
